import pygame
class Move_img(pygame.sprite.Sprite):
    def __init__(self,image,init_x,init_y,visible):
        super().__init__()
        self.image = image
        self.rect = self.image.get_rect()
        #保存初始位置
        self.init_x = init_x
        self.init_y = init_y
        self.rect.x = self.init_x
        self.rect.y = self.init_y
        self.dire = 'x'
        self.speed = 0
        self.visible = visible
        self.moving = True
        self.alive = True

    def img_move(self,dire,speed):
        self.dire = dire
        self.speed = speed
        #判断方向
        if dire == 'x':
            self.rect.x += speed
            #判断速度是正是负
            if speed>0:
                if self.rect.x >= self.init_x+self.rect.width:
                    self.rect.x = min(self.rect.x,self.init_x+self.rect.width)
                    self.moving = False
                    self.speed = 0
                    self.alive = False
            else:
                if self.rect.x <= self.init_x-self.rect.width:
                    self.rect.x = max(self.rect.x, self.init_x - self.rect.width)
                    self.moving = False
                    self.speed = 0
                    self.alive = False
        if dire=='y':
            self.rect.y += speed
            if speed>0:
                if self.rect.y >= self.init_y+self.rect.height:
                    self.rect.y = min(self.rect.y, self.init_y + self.rect.height)
                    self.moving = False
                    self.speed = 0
                    self.alive = False
            else:
                if self.rect.y <= self.init_y-self.rect.height:
                    self.rect.y = max(self.rect.y, self.init_y - self.rect.height)
                    self.moving = False
                    self.speed = 0
                    self.alive = False

    def move_img_display(self,window):
        #获取原先屏幕的裁剪区域
        original_clip = window.get_clip()
        #设置现在屏幕的裁剪区域  （只有裁剪区域里的事物才能被改变）
        if self.visible == True:
            window.set_clip((self.init_x,self.init_y,self.rect.width,self.rect.height))
        else:
            if (self.dire=='x')and(self.speed<0):
                window.set_clip((self.init_x-self.rect.width, self.init_y, self.rect.width, self.rect.height))
            elif (self.dire=='x')and(self.speed>0):
                window.set_clip((self.init_x+self.rect.width, self.init_y, self.rect.width, self.rect.height))
            elif (self.dire=='y')and(self.speed<0):
                window.set_clip((self.init_x, self.init_y-self.rect.height, self.rect.width, self.rect.height))
            elif (self.dire=='y')and(self.speed>0):
                window.set_clip((self.init_x, self.init_y+self.rect.height, self.rect.width, self.rect.height))
        #将图片添加到屏幕上
        window.blit(self.image,self.rect)
        #设置回原先的裁剪区域
        window.set_clip(original_clip)